import { Condition } from './../domain/models/condition';
import { Transaction } from "tiny-entity2";
import { IQueryObject } from "tiny-entity2/queryObject";
import { compareDataField } from "../common/utils/condition-tool";
import { ApiDataContext } from "../domain/apiDataContext";
import { Message } from "../domain/models/message";
import { BaseService } from "./baseService";

export class MessageService extends BaseService {
    private cleanMsgTimer;

    CreateMessage(entity: Message, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new Message();
            d.ConverToEntity(entity);
            return ctx.Create(d);
        });
    }
    UpdateMessage(entity: Message, ctx?: ApiDataContext) {
        ctx || (ctx = new ApiDataContext());
        return Transaction(ctx, async (ctx) => {
            let d = new Message();
            d.ConverToEntity(entity);
            return ctx.Update(d);
        });
    }
    GetMessageById(id: string) {
        let ctx = new ApiDataContext();
        return ctx.Message.First(x => x.id == $args1, { $args1: id });
    }
    QueryMessage(params: IMessageQueryParams) {
        let ctx = new ApiDataContext();
        let q = ctx.Message as IQueryObject<Message>;
        if (params) {
            if (params.orgId) {
                q = q.Where(x => x.orgId == $args1, { $args1: params.orgId });
            }
            if (params.senderId) {
                q = q.Where(x => x.senderId == $args1, { $args1: params.senderId });
            }
            if (params.status) {
                q = q.Where(x => x.status == $args1, { $args1: params.status });
            }
            if (params.receiverIds) {
                q = q.Where(x => x.receiverIds.indexOf($args1), { $args1: params.receiverIds });
            }
        }

        return q.OrderByDesc(x => x.createTime).ToList();
    }

    CleankStart() {
        // 十分钟执行一次清除任务
        this.cleanMsgTimer = setInterval(this.CleanMessageHandle.bind(this), 1000 * 60 * 1);
    }

    CleanStop() {
        clearInterval(this.cleanMsgTimer);
        this.cleanMsgTimer = null;
    }

    async CleanMessageHandle() {
        this.CleanStop();
        try {
            let ctx = new ApiDataContext();
            //.Take(100)

            const msgList = await ctx.Message.Where(x => x.conditionSentence != null).ToList();
            console.log(`已获取到消息，开始判断清除条件！`);
            for (let item of msgList) {
                if (!item.conditionSentence || !item.dataRegisterId) continue;
                try {
                    const dataRegister = await ctx.DataRegister.First(x => x.id == $args1, { $args1: item.dataRegisterId });
                    if (!dataRegister || !dataRegister.data) {
                        await ctx.Delete(item);
                        continue;
                    }
                    const dataModel = dataRegister.data.fields;

                    let condition = new Condition();
                    condition.sentence = item.conditionSentence;

                    const result = compareDataField(dataModel, condition);
                    if (result) {
                        //满足删除条件
                        await ctx.Delete(item);
                        console.log(`已删除消息【${item.body}】!!`);
                    }
                    else {
                        const dataModel = dataRegister.data.fields;

                        let condition = new Condition();
                        condition.sentence = item.conditionSentence;

                        const result = compareDataField(dataModel, condition);
                        if (result) {
                            //满足删除条件
                            await ctx.Delete(item);
                            console.log(`已删除消息【${item.body}】!`);
                        }
                    }
                }
                catch (error) {
                    console.log("compareDataField:", error);
                }
            }
        } catch (error) {
            console.log(error);
        }
        finally {
            this.CleankStart();
        }
    }
}

export interface IMessageQueryParams {
    orgId?: string;
    senderId?: string;
    receiverIds?: string[]
    status?: string;
}